package com.TexasHoldem.ServerData.Quest;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService;
import com.TexasHoldem.RpcInterface.rpc.TexasHoldemService.QuestList.Builder;
import com.TexasHoldem.ServerData.PokerPlayer;
import com.TexasHoldem.db.TexasHoldemDB;

/**
 * @author su
 * 在线时间奖励
 *
 */
public class PlayerOnlineAwardQuest implements PokerQuest
{
	public Long id;
	public long onlineTime = 0;
	// 保存获胜任务进度 在线时间目标=>当前进度_完成状态
	public Map<String,String> onlinestatus = new HashMap<String,String>();
	public PokerPlayer pokerplayer;
	@Override
	public void OnQuestProcess()
	{
		if(pokerplayer.getStatistics().getLoginTime().get() == 0)
			return;
		// TODO Auto-generated method stub
		onlineTime = pokerplayer.getStatistics().getActiveTime().get() - pokerplayer.getStatistics().getLoginTime().get();
		
		for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_onlinequest())
		{
			if(onlinestatus.containsKey(qd.getOnlinemintime()))
			{
				Integer queststate = Integer.parseInt(onlinestatus.get(qd.getOnlinemintime()).split("_")[1]);
				
				if(queststate != QUEST_AWARED)
				{
					if(onlineTime >= Integer.parseInt(qd.getOnlinemintime()) * 60 * 1000  )
						onlinestatus.put(qd.getOnlinemintime(), String.format("%d_%d", Integer.parseInt(qd.getOnlinemintime()),QUEST_FINISH));
					else
						onlinestatus.put(qd.getOnlinemintime(), String.format("%d_%d", onlineTime,QUEST_UNFINISH));
				}
			}
			else
			{
				if(onlineTime >= Integer.parseInt(qd.getOnlinemintime()) * 60 * 1000 )
					onlinestatus.put(qd.getOnlinemintime(), String.format("%d_%d", Integer.parseInt(qd.getOnlinemintime()),QUEST_FINISH));
				else
					onlinestatus.put(qd.getOnlinemintime(), String.format("%d_%d", onlineTime,QUEST_UNFINISH));
			}
		}
	}


	@Override
	public void OnInit(PokerPlayer pokerplayer)
	{
		// TODO Auto-generated method stub
		this.pokerplayer = pokerplayer;
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerOnlineAwardQuest.class.getSimpleName()).getQuestid();
		Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
		QueryRunner qr = new QueryRunner();
		String sql = "select id,player_id,questdata from playerquest where player_id=? and questId=?";
	    try {
	    	List results = (List) qr.query(c,sql, new BeanListHandler(QuestBean.class), pokerplayer.getId(),questid);
	    	
	    	for (int i = 0; i < results.size(); i++) {
	    		QuestBean gb = (QuestBean) results.get(i);
	    		this.id = gb.getId();
	    		this.onlinestatus.putAll(JSONObject.fromObject(gb.getQuestdata()));
            }
	    	
	    } catch (SQLException e) {
	        e.printStackTrace();
	    }
	    finally
	    {
	    	DbUtils.closeQuietly(c);
	    }
	}

	@Override
	public void OnFinish(int questId,String questAwardParam)
	{
		// TODO Auto-generated method stub
		QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerOnlineAwardQuest.class.getSimpleName());
		
		if(ql.getQuestid() != questId)
			return;
		
		
		if(onlinestatus.containsKey(questAwardParam))
		{
			Integer queststate = Integer.parseInt(onlinestatus.get(questAwardParam).split("_")[1]);
			if(queststate != QUEST_AWARED)
			{
				for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_onlinequest())
				{
					if(qd.getOnlinemintime().equals(questAwardParam))
					{
						pokerplayer.setYXB(pokerplayer.getYXB() + Integer.parseInt(qd.getAward()));
						
						onlinestatus.put(questAwardParam, String.format("%s_%d", questAwardParam,QUEST_AWARED));
						break;
					}
						
				
				}

			}
		}
		
	}

	@Override
	public void OnSave()
	{
		// TODO Auto-generated method stub
		JSONObject js = new JSONObject();
		js.putAll(onlinestatus);
		Integer questid = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerOnlineAwardQuest.class.getSimpleName()).getQuestid();
		if(id != null)
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "update playerquest set player_id=?,questdata=?,questId=? where id=?";
		    try {
		        qr.update(c, sql, pokerplayer.getId(),js.toString(),questid,this.id);
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
		else
		{
			Connection c = TexasHoldemDB.getDBConnUitl().GetConnection();
			QueryRunner qr = new QueryRunner();
			String sql = "insert into playerquest (player_id, questdata,questId) values (?,?,?)";
		    try {
		    	qr.update(c, sql, pokerplayer.getId(),js.toString(),questid);
		        BigInteger newId = (BigInteger) qr.query(c, "select last_insert_id()", new ScalarHandler<BigInteger>(1));
		        this.id = newId.longValue();
		    } catch (SQLException e) {
		        e.printStackTrace();
		    }
		    finally
		    {
		    	DbUtils.closeQuietly(c);
		    }
		}
	}
	
	@Override
	public void toQuest(Builder qb)
	{
		// TODO Auto-generated method stub
		QuestImpleMap ql = PokerQuestRule.getPokerQuestRule().getQuestname_factory().get(PlayerOnlineAwardQuest.class.getSimpleName());
		
		for(String onlinetime:onlinestatus.keySet())
		{
			TexasHoldemService.Quest.Builder quest = TexasHoldemService.Quest.newBuilder();

			for(QuestData qd:PokerQuestRule.getPokerQuestRule().getEvery_onlinequest())
			{
				if(onlinetime.equals(qd.getOnlinemintime()) && onlinestatus.containsKey(onlinetime))
				{
					
					Integer queststate = Integer.parseInt(onlinestatus.get(qd.getOnlinemintime()).split("_")[1]);
					if(queststate == QUEST_FINISH)
					{
						quest.setAward(Integer.parseInt(qd.getAward()));
						quest.setCur(1);
						quest.setEnd(1);
						quest.setName(ql.getDesc() + onlinetime + "分钟");
						quest.setQuestId(ql.getQuestid());
						quest.setQuestAwardparam(qd.getOnlinemintime());
						qb.addQuests(quest);
					}
					
					
				}
				
			}

			
			
		}
	}

}
